package com.kll.tv.views.fragment.main

import android.content.ComponentName
import android.content.Intent
import android.os.Build
import android.os.Environment
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.core.content.FileProvider
import com.hihonor.android.app.admin.DevicePackageManager
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.model.AccountModel
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.DownloadFileProgress
import com.kll.carolinehmibiz.net.bean.GetAppNewlyVersionResponse
import com.kll.carolinehmibiz.net.bean.RefreshTokenResponse
import com.kll.carolinehmibiz.presentation.listener.SettingProtocol
import com.kll.carolinehmibiz.presentation.presenter.SettingPresenter
import com.kll.tv.R
import com.kll.tv.SampleDeviceReceiver
import com.kll.tv.base.views.MainBaseFragment
import com.kll.tv.databinding.FragmentMainSettingBinding
import com.kll.tv.utils.AppToast
import com.kll.tv.views.AccountSafetyActivity
import com.kll.tv.views.LoginActivity
import com.kll.tv.views.SwitchAccountActivity
import com.kll.tv.views.ui.AlertDialog
import com.kll.tv.views.ui.CircleBarView
import com.kll.tv.views.ui.listener.AlertDialogTypeEnum
import java.io.File


/**
 * ====================================================
 * Created by Ziliang Cai on 2021/12/7 22:19
 * <a href="mailto:752777456@qq.com">Contact me</a>
 * ====================================================
 */
class MainSettingFragmengt: MainBaseFragment<SettingPresenter>(), SettingProtocol.IView {
    private lateinit var binding: FragmentMainSettingBinding
    private var progressCbv: CircleBarView? = null // 下载进度
    private var progressTv: TextView? = null // 下载百分比
    private var loadingAlert: AlertDialog? = null
    private val versionName by lazy { requireContext().packageManager.getPackageInfo(requireContext().packageName, 0).versionName }

    override fun createPresenter(): SettingPresenter {
        return SettingPresenter(requireContext(), this)
    }

    override fun initViewBinding(): View {
        binding = FragmentMainSettingBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun init() {
        binding.tvVersion.text = versionName+"设备码${AccountModel.SN}"

        initListener()
    }

    private fun initListener() {
        // 账号与安全
        binding.tvAccountSecurity.setOnClickListener {
            startActivity(Intent(context, AccountSafetyActivity::class.java))
        }
        // 多语言
        binding.tvLanguage.setOnClickListener {
            AppToast.show("敬请期待！", 2000)
        }
        // 清理缓存
        binding.tvClearCache.setOnClickListener {
            AppToast.show("敬请期待！", 2000)
        }
        // 版本更新
        binding.tvAboutCaroline.setOnClickListener {
            mPresenter.getAppNewlyVersion()
        }
        // 切换账号
        binding.tvSwitchAccount.setOnClickListener {
            startActivity(Intent(context, SwitchAccountActivity::class.java))
        }
        // 退出登录
        binding.tvSignOut.setOnClickListener {
            mPresenter.logout()
            startActivity(Intent(context, LoginActivity::class.java))
            AppToast.show("退出登录成功！", 2000)
        }
    }

    /**
     * 有新版本
     */
    override fun getAppNewlyVersionTrue(versionInfo: GetAppNewlyVersionResponse) {
        var alert = AlertDialog.createTip(activity, "提示", "发现新版本：${versionInfo.versioncode}")
        alert.setButton("更新", "取消")
        alert.setOnClickListener { type, view ->
            when(type) {
                AlertDialogTypeEnum.CANCEL -> alert.dismiss()
                AlertDialogTypeEnum.OK -> {
                    // 开始下载文件
                    var dataFile = "";
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        dataFile = "${requireContext().cacheDir.absolutePath}/${System.currentTimeMillis()}.apk"
                    } else {
                        dataFile = "${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)}/${System.currentTimeMillis()}.apk"
                    }
                    mPresenter.downloadFile(versionInfo.url, dataFile)
                    val view = LayoutInflater.from(context).inflate(R.layout.item_alert_loading, null)
                    loadingAlert = AlertDialog.createCustom(context, view)
                    val tipTv = loadingAlert!!.findViewById<TextView>(R.id.tv_something)
                    progressCbv = loadingAlert!!.findViewById<CircleBarView>(R.id.cbv_progress)
                    progressTv = loadingAlert!!.findViewById<TextView>(R.id.tv_progress)
                    tipTv.text = "下载中..."
                    loadingAlert!!.show()
                }
            }
        }
        alert.show()
    }

    /**
     * 无新版本
     */
    override fun getAppNewlyVersionFalse() {
        AppToast.show("当前已经是最新版本，无需更新!", 2000)
    }

    /**
     * 失败
     */
    override fun getAppNewlyVersionFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(context!!).updateUserToken(data.token)
                    mPresenter.getAppNewlyVersion()
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }



    /**
     * 下载文件成功
     */
    override fun downloadFileSuccessed(data: DownloadFileProgress, savePath: String) {
        progressCbv!!.currentValue = (data.progress.toFloat() / data.fileSize * 100).toInt()
        progressTv!!.text = "${(data.progress.toFloat() / data.fileSize * 100).toInt()}%"

        if(data.isFinshed) {
            loadingAlert!!.dismiss()
            // 打开apk安装界面(调用静默安装器）
            var contentUri=FileProvider.getUriForFile(requireActivity(),"com.kll.tv.fileprovider",
                File(savePath)
            )
            requireActivity().grantUriPermission("android",contentUri,Intent.FLAG_GRANT_READ_URI_PERMISSION)
            DevicePackageManager().installPackage(
                ComponentName(requireContext(),
                    SampleDeviceReceiver::class.java),contentUri .toString())
           //mPresenter.openInstallPage(savePath)
        }
    }

    /**
     * 下载文件失败
     */
    override fun downloadFileFailed(message: String) {
        AppToast.show(message, 2000)
    }
}